package edu.cuit.zhuyimeng.flight.delegate;

import edu.cuit.zhuyimeng.flight.controller.vo.FlightInfoVO;
import edu.cuit.zhuyimeng.flight.service.IFlightQueryService;
import edu.cuit.zhuyimeng.flight.service.IJobDispatchService;
import edu.cuit.zhuyimeng.framework.common.exception.UpdateException;
import edu.cuit.zhuyimeng.framework.common.system.enums.SysConstants;
import edu.cuit.zhuyimeng.framework.common.util.TimeUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.springframework.stereotype.Component;
import tech.powerjob.client.PowerJobClient;
import tech.powerjob.common.enums.ExecuteType;
import tech.powerjob.common.enums.ProcessorType;
import tech.powerjob.common.enums.TimeExpressionType;
import tech.powerjob.common.request.http.SaveJobInfoRequest;
import tech.powerjob.common.response.ResultDTO;

/**
 * 开放订票委托类（上传开放订票的调度任务）
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class TicketDelegate implements JavaDelegate {

    private final IFlightQueryService flightQueryService;
    private final IJobDispatchService jobDispatchService;

    private final PowerJobClient powerJobClient;

    private final RuntimeService runtimeService;

    @Override
    public void execute(DelegateExecution execution) {
        FlightInfoVO flightInfoVO = flightQueryService.queryOneFlight(Long.parseLong(execution.getProcessInstanceBusinessKey()));
        log.info("航班 {} 开始设置调度任务（开放订票）...", flightInfoVO.getNumber());

        ResultDTO<Long> longResultDTO = jobDispatchService.startReleaseTicketJob(flightInfoVO);

        execution.setVariable(SysConstants.JOB_ID_KEY,longResultDTO.getData());

        if (longResultDTO.isSuccess()) {
            log.info("航班 {} 设置调度任务（开放订票）完毕",flightInfoVO.getNumber());
        } else {
            log.error("航班 {} 设置调度任务（开放订票）失败: {}",flightInfoVO.getNumber(),longResultDTO.getMessage());
            runtimeService.deleteProcessInstance(execution.getProcessInstanceId(),"创建航班出错");
            throw new UpdateException(longResultDTO.getMessage());
        }
    }

}
